<?php
require_once 'config.php';
session_start();
require_once 'login_check.php';
require_once __DIR__ . '/vendor/autoload.php';
require_once 'manage_index.php'; // 引入侧边栏渲染文件
use PhpOffice\PhpSpreadsheet\IOFactory;
check_admin_session();

// 处理Excel导入
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_excel'])) {
    // 校验文件上传
    if ($_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
        echo "<script>alert('文件上传失败：{$_FILES['excel_file']['error']}');</script>";
        exit;
    }
    // 校验文件类型
    $allowedExt = ['xls', 'xlsx'];
    $ext = pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION);
    $allowedMime = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];
    if (!in_array($ext, $allowedExt) || !in_array($_FILES['excel_file']['type'], $allowedMime)) {
        echo "<script>alert('仅支持 Excel 文件（.xls/.xlsx）');</script>";
        exit;
    }
    // 保存文件
    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    $fileName = uniqid() . '.' . $ext;
    $filePath = $uploadDir . $fileName;
    if (!move_uploaded_file($_FILES['excel_file']['tmp_name'], $filePath)) {
        echo "<script>alert('文件保存失败，请检查目录权限');</script>";
        exit;
    }
    // 读取并解析Excel
    try {
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $headerRow = $sheet->rangeToArray('A1:N1')[0]; // 读取A1到N1的表头
        $expectedHeaders = [
            '时间', '班级', 
            '周一课程', '周一教室', 
            '周二课程', '周二教室', 
            '周三课程', '周三教室', 
            '周四课程', '周四教室', 
            '周五课程', '周五教室', 
            '周六课程', '周六教室'
        ];
        
        if ($headerRow !== $expectedHeaders) {
            throw new Exception('Excel表头格式不符，请使用模板（时间、班级、周一课程/教室...周六课程/教室）');
        }
        // 周几映射关系
        $weekdayMap = [
            'monday' => ['course_col' => 2, 'location_col' => 3],
            'tuesday' => ['course_col' => 4, 'location_col' => 5],
            'wednesday' => ['course_col' => 6, 'location_col' => 7],
            'thursday' => ['course_col' => 8, 'location_col' => 9],
            'friday' => ['course_col' => 10, 'location_col' => 11],
            'saturday' => ['course_col' => 12, 'location_col' => 13]
        ];
        $successCount = 0;
        $errorCount = 0;
        $errorMessages = [];
        // 从第2行开始读取数据
        for ($row = 2; $row <= $sheet->getHighestRow(); $row++) {
            $rowData = $sheet->rangeToArray("A{$row}:N{$row}", null, true, true, true)[$row];
            $courseTime = trim($rowData['A']);
            $className = trim($rowData['B']);
            if (empty($courseTime) || empty($className)) {
                $errorMessages[] = "第{$row}行：时间或班级为空";
                $errorCount++;
                continue;
            }
            // 遍历周一至周六
            foreach ($weekdayMap as $weekday => $cols) {
                $courseCol = chr(65 + $cols['course_col']);
                $locationCol = chr(65 + $cols['location_col']);
                $courseName = trim($rowData[$courseCol]);
                $courseLocation = trim($rowData[$locationCol]) ?: '未指定';
                if (empty($courseName)) continue;
                $courseDate = date('Y-m-d', strtotime("this week $weekday"));
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO course_schedule (
                            class_name, course_date, course_time, course_name, 
                            course_location, weekday
                        ) VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $className, $courseDate, $courseTime, 
                        $courseName, $courseLocation, $weekday
                    ]);
                    $successCount++;
                } catch (PDOException $e) {
                    $errorMessages[] = "第{$row}行（{$weekday}）：{$e->getMessage()}";
                    $errorCount++;
                }
            }
        }
        // 清理临时文件
        unlink($filePath);
        // 导入结果提示
        $msg = "成功导入{$successCount}条记录";
        if ($errorCount > 0) {
            $msg .= "，失败{$errorCount}条：" . implode('；', $errorMessages);
        }
        echo "<script>alert('{$msg}'); window.location.href='course_schedule_manage.php';</script>";
    } catch (Exception $e) {
        unlink($filePath);
        echo "<script>alert('导入失败：{$e->getMessage()}');</script>";
    }
    exit;
}

// 添加 weekday 字段到数据库表（如果不存在）
function addWeekdayColumn($pdo) {
    try {
        $pdo->exec("ALTER TABLE course_schedule ADD COLUMN weekday VARCHAR(20) AFTER course_date");
        echo "已成功添加 'weekday' 字段<br>";
    } catch (PDOException $e) {
        // 如果字段已存在，忽略错误
        if (strpos($e->getMessage(), "Duplicate column name 'weekday'") === false) {
            echo "添加字段失败: " . $e->getMessage() . "<br>";
            return false;
        }
    }
    return true;
}

// 根据日期更新 weekday 字段
function updateWeekdayFromDate($pdo) {
    // 获取所有没有 weekday 值的记录
    $stmt = $pdo->query("SELECT id, course_date FROM course_schedule WHERE weekday IS NULL OR weekday = ''");
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $weekdayMap = [
        0 => 'sunday',
        1 => 'monday',
        2 => 'tuesday',
        3 => 'wednesday',
        4 => 'thursday',
        5 => 'friday',
        6 => 'saturday'
    ];
    
    $updatedCount = 0;
    
    foreach ($records as $record) {
        $date = $record['course_date'];
        $dayOfWeek = date('w', strtotime($date));
        $weekday = $weekdayMap[$dayOfWeek];
        
        $updateStmt = $pdo->prepare("UPDATE course_schedule SET weekday = :weekday WHERE id = :id");
        $updateStmt->bindParam(':weekday', $weekday);
        $updateStmt->bindParam(':id', $record['id']);
        
        if ($updateStmt->execute()) {
            $updatedCount++;
        }
    }
    
    return $updatedCount;
}

// 获取所有班级
function getAllClasses($pdo) {
    $stmt = $pdo->query("SELECT DISTINCT class_name FROM course_schedule ORDER BY class_name");
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}


// 处理删除课程
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM course_schedule WHERE id = :id");
    $stmt->bindParam(':id', $id);
    if ($stmt->execute()) {
        $_SESSION['message'] = '课程删除成功';
    } else {
        $_SESSION['message'] = '课程删除失败';
    }
    header('Location: course_schedule_manage.php');
    exit;
}

// 处理添加课程
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_course'])) {
    $class_name = $_POST['class_name'];
    $weekday = $_POST['weekday'];  // 存储星期几（如 'monday'）
    $course_time = $_POST['course_time']; // 保留原始时间格式（如“第一二节”）
    $course_name = $_POST['course_name'];
    $course_location = $_POST['course_location'];
    
    // 根据选择的星期几计算日期（本周）
    $course_date = date('Y-m-d', strtotime("this week $weekday"));
    $stmt = $pdo->prepare("
        INSERT INTO course_schedule (class_name, course_date, course_time, course_name, course_location, weekday)
        VALUES (:class_name, :course_date, :course_time, :course_name, :course_location, :weekday)
    ");
    $stmt->bindParam(':class_name', $class_name);
    $stmt->bindParam(':course_date', $course_date);
    $stmt->bindParam(':course_time', $course_time);
    $stmt->bindParam(':course_name', $course_name);
    $stmt->bindParam(':course_location', $course_location);
    $stmt->bindParam(':weekday', $weekday);
    
    if ($stmt->execute()) {
        $_SESSION['message'] = '课程添加成功';
    } else {
        $_SESSION['message'] = '课程添加失败';
    }
    header('Location: course_schedule_manage.php');
    exit;
}

// 处理数据库更新请求
if (isset($_GET['update_db'])) {
    if (addWeekdayColumn($pdo)) {
        $count = updateWeekdayFromDate($pdo);
        echo "成功更新 {$count} 条记录的 weekday 字段<br>";
    }
    echo '<a href="course_schedule_manage.php">返回课表管理</a>';
    exit;
}


// 星期几映射表（用于表单和显示）
$weekdayMap = [
    'monday' => '周一',
    'tuesday' => '周二',
    'wednesday' => '周三',
    'thursday' => '周四',
    'friday' => '周五',
    'saturday' => '周六',
    'sunday' => '周日'
];

// 获取所有班级
$classes = getAllClasses($pdo);

// 主页URL
$homeUrl = "course_schedule_display.php";

// 页面标题设置
$pageTitle = "课表展示";
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <!-- 图标库依赖（侧边栏使用） -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">
    <style>
        /* 主内容区域样式（与侧边栏配合） */
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
            background: #f5f7fa;
        }
        .main-content {
            margin-left: 240px; /* 与侧边栏宽度匹配 */
            width: 100%;
            padding: 48px 32px 32px 32px;
            box-sizing: border-box;
        }
        .manage-panel {
            max-width: 1000px;
            margin: 0 auto;
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 18px rgba(41, 128, 255, 0.08);
            padding: 32px;
        }
        .config-form {
            background-color: #f0f0f0;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        .config-form label {
            margin-right: 15px;
        }
        .config-form input,
        .config-form select {
            padding: 6px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        /* 按钮样式 */
        .btn {
            display: inline-block;
            padding: 8px 16px;
            background: #2980ff;
            color: #fff;
            text-decoration: none;
            border-radius: 6px;
            margin-top: 5px;
            border: none;
            cursor: pointer;
            transition: background 0.2s;
        }
        .btn:hover {
            background: #1866d1;
        }
        .btn.import {
            background-color: #17a2b8;
        }
        /* 表格样式 */
        .schedule-table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            margin-top: 20px;
        }
        .schedule-table th,
        .schedule-table td {
            border: 1px solid #ccc;
            padding: 12px;
            text-align: center;
            vertical-align: middle;
            font-size: 14px;
        }
        .schedule-table th {
            background: #f1f3f5;
            font-weight: 600;
        }
        .schedule-table td {
            white-space: normal;
            word-wrap: break-word;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: inline-block;
            margin-right: 15px;
        }
        .form-control {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            min-width: 200px;
        }
        /* 响应式适配（与侧边栏同步） */
        @media (max-width: 900px) {
            .main-content {
                margin-left: 56px;
                padding: 24px 12px;
            }
            .manage-panel {
                padding: 16px;
            }
        }
    </style>
</head>
<body>
    <?php render_sidebar(); // 渲染侧边栏（与time_manage保持一致） ?>
    
    <div class="main-content"> <!-- 主内容容器（关键：与侧边栏分离） -->
        <div class="manage-panel">
            <h2><span class="mdi mdi-table"></span>课表展示</h2>
            
            <?php if (isset($_SESSION['message'])): ?>
                <div class="message <?php echo strpos($_SESSION['message'], '成功')!== false ? 'success' : 'error'; ?>">
                    <?php echo htmlspecialchars($_SESSION['message']); ?>
                </div>
                <?php unset($_SESSION['message']); ?>
            <?php endif; ?>

            <!-- Excel导入表单 -->
            <form action="course_schedule_manage.php" method="post" enctype="multipart/form-data" class="form-group">
                <input type="file" name="excel_file" accept=".xls,.xlsx" required>
                <button type="submit" name="import_excel" class="btn import">导入Excel课表</button>
            </form>

            <!-- 添加课程表单 -->
            <form method="post" class="form-group">
                <input type="hidden" name="add_course" value="1">
                
                <label>班级: <input type="text" name="class_name" class="form-control" required></label>
                
                <label>星期: 
                    <select name="weekday" class="form-control" required>
                        <option value="">选择星期</option>
                        <option value="monday">周一</option>
                        <option value="tuesday">周二</option>
                        <option value="wednesday">周三</option>
                        <option value="thursday">周四</option>
                        <option value="friday">周五</option>
                        <option value="saturday">周六</option>
                        <option value="sunday">周日</option>
                    </select>
                </label>
                
                <label>时间: <input type="text" name="course_time" class="form-control" placeholder="如“第一二节”" required></label>
                
                <label>课程: <input type="text" name="course_name" class="form-control" required></label>
                
                <label>地点: <input type="text" name="course_location" class="form-control" required></label>
                
                <button class="btn" type="submit">添加课程</button>
            </form>

            <!-- 课程列表 -->
            <h3>现有课程</h3>
            <table class="schedule-table">
                <tr>
                    <th>班级</th>
                    <th>星期</th>
                    <th>日期</th>
                    <th>时间</th>
                    <th>课程</th>
                    <th>地点</th>
                    <th>操作</th>
                </tr>
                <?php
                // 获取所有课程
                $stmt = $pdo->query("SELECT * FROM course_schedule ORDER BY FIELD(weekday, 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'), course_time");
                $allSchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if (empty($allSchedule)): ?>
                    <tr>
                        <td colspan="7" style="padding: 20px;">暂无课程数据</td>
                    </tr>
                <?php else:
                    foreach ($allSchedule as $row): ?>
                        <tr>
                            <td><?php echo $row['class_name']; ?></td>
                            <td><?php echo $weekdayMap[$row['weekday']]; ?></td>
                            <td><?php echo $row['course_date']; ?></td>
                            <td><?php echo $row['course_time']; ?></td>
                            <td><?php echo $row['course_name']; ?></td>
                            <td><?php echo $row['course_location']; ?></td>
                            <td>
                                <a href="course_schedule_manage.php?delete=<?php echo $row['id']; ?>" class="btn" onclick="return confirm('确定删除？')">删除</a>
                            </td>
                        </tr>
                    <?php endforeach;
                endif; ?>
            </table>
        </div>
    </div>
</body>
</html>